JavaScript String Methods

    In the previous tutorial, we learned about JavaScript string and how a primitive JavaScript string is different from the JavaScript String() object. As an object can have properties and methods, similarly, various methods and properties are associated with the JavaScript String object. Although both primitive string data types and String() object data types are different in many cases, JavaScript still treats both the strings similarly and makes sure that all the properties and methods available for String() objects also apply to the primitive string data type.

    String length

    The string has a length property that returns the total number of characters present in the string.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz";
        var len = text.length
        console.log(len)
    </script>

    Output

    33

    Find substring in a String

    With the help of indexOf() method, we can find the starting index of the substring in the given string. The indexOf() method will return the index value of the first occurrence of the substring. If the substring is not present in the string the method returns -1.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = "Hi";
        console.log(text.indexOf(sub));
    </script>

    Output

    0

    The sub="Hi" start at the 0th index of the string text . If you want to find the last occurrence of the substring in a given string, then you can use the lastIndexOf() method. It returns the last occurrence of the substring in a given string.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = "Hi";
        console.log(text.lastIndexOf(sub));
    </script>
    Output
    34

    In the above example, the lastIndexOf() method returns the last occurrence Index value of the substring Hi . Both lastIndexOf() and indexOf() string methods accept an optional second parameter that specifies the starting index value from where the substring search should begin.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = "Hi";
        var position = text.indexOf(sub, 2); // start serching from 2nd index value
        console.log(position)
    </script>
    Output
    34
    Behind the code In the above example the position = text.indexOf(sub, 2); statement will start searching the index value of sub string in the text string from index value 2. This means it will skip the first 2 index characters of the text .

    Search string within a string in JavaScript

    JavaScript string also support search() methods that return the first occurrence index value of the searched string within a string. And similar to indexOf() method the search() return -1 if the substring is not present in the given string. Example
    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = "Hi";
        var position = text.search(sub);
        console.log(position)
    </script>
    Output
    0
    In the above example the search() method worked similar to the indexOf() method, as it returns the first occurrence index value of sub in text . Although both the method return the same result still they have their own specific usages. The search(substring) method only accepts the substring as a parameter but indexOf(substring, start_index) can accept substring as well as the start index value from where the searching should perform. The search() method can work with regular expressions which makes it a more advanced searching method as compared to indexOf() which does not support regular expressions. We will be discussing how JavaScript Regular Expressions in upcoming tutorials.

    JavaScript string slice() Method

    The JavaScript string slice() method can extract a sequence of a substring from the string.

    Syntax

    string.slice(start,end)

    The slice() method can accept two parameters start , and end that represent the starting and ending index of the sliced substring. The end index value does not include by the slice method, which means it will only extract the string from start to end-1.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = text.slice(4, 16);
        console.log(sub);
    </script>
    Output
    There welcom
    Behind the code In the above example the text.slice(4,6); statement will extract the substring from text from index value 4 to 16(excluded).

    We can also specify the -ve integer values if we want to extract the string from the back.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = text.slice(-16, -4);
        console.log(sub);
    </script>

    Output

    techgeekbuzz

    In -ve integer index value, -1 represents the last character of the string, -2 represents the second last, and so on. In the slice() method both the parameters are optional. If we do not specify any of the parameters the slice() method will return the complete string.

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = text.slice();
        console.log(sub);
    </script>

    Output

    Hi! There welcome to techgeekbuzz Hi!

    If we specify the single parameter it will take it as a start parameter and slice the string from the specified parameter to the end.

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = text.slice(4);// slice from 4 up to end
        console.log(sub);
    </script>
    Output
    There welcome to techgeekbuzz Hi!

    JavaScript string substring() method

    As the name suggests we can find the substring(), method returns the substring of the given string. The substring() method is similar to the slice() a method, the only difference is, it does not accept -ve parameters. Syntax

    string.substring(start,end)

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = text.substring(4, 8);// slice from 4 up to 8(exclude) 
        console.log(sub);
    </script>
    Output
    Ther

    JavaScript string substr() method

    The substr() method is also used to extract the substring from a given string.

    Syntax string.substr(start, length); The substr() method accepts two parameters start that represent the starting index value from where the string slicing should perform and the length parameter represents the length of the sliced string.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var sub = text.substr(4, 6);// slice 6 charecter long substring from 4th index 
        console.log(sub);
    </script>
    Output
    There

    JavaScript string replace() method

    The replace() method is used to replace some value of the given string with another value. The replace() method does not change the string on which it is applied instead it returns a new string.

    Syntax

    string.replace(old_value, new_value)

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var new_string= text.replace("Hi", "hello") 
        console.log(new_string);
    </script>
    Output
    hello! There welcome to techgeekbuzz Hi!
    In the above example, you can see that the replace() method will only replace the first occurrence value with the new value. The replace() method can also work with regular expressions that we will discuss in the upcoming tutorial.

    Convert JavaScript string to uppercase

    JS string also provides the toUpperCase() method, that converts all the string characters to uppercase and returns a new string.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var up_text = text.toUpperCase()
        console.log(up_text);
    </script>

    Output

    HI! THERE WELCOME TO TECHGEEKBUZZ HI!

    Convert JavaScript string to lowercase

    Similar to toUpperCase() method we have toLowerCase() method converts all the string characters to lowercase alphabets and returns a new string of lower case.

    Example

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var low_text = text.toLowerCase()
        console.log(low_text);
    </script>
    Output
    hi! there welcome to techgeekbuzz hi!

    Concatenate two strings in JavaScript

    To concatenate two strings in JavaScript, we can use the string concat() method or + operator.

    Example

    <script>
        var text1 = "Hi!";
        var text2 = "There"
        var join = text1.concat(" ", text2);
        console.log(join);
    </script>
    Output
    Hi! There
    The above same concatenation example can be performed using + operator.
    <script>
        var text1 = "Hi!";
        var text2 = "There";
        var join = text1 + " " + text2;
        console.log(join);
    </script>
    Output
    Hi! There

    Trim WhiteSpace from string

    The string also treats the whitespace as an individual character, and if you want to remove the extra whitespaces from the starting and end of a string then you can use the trim() method.

    Example

    <script>
        var text1 = "            Hi!          ";
        var text2 = text1.trim();
        console.log("length of text1 is: "+ text1.length)
        console.log("length of text2 is: "+ text2.length)
    </script>

    Output

    length of text1 is: 25
    length of text2 is: 3

    Convert a JS string to an Array

    split() is one of the most used and powerful string methods, it can convert a given string into an array. It does not convert the actual string into an array instead it returns a new array based on the string.

    Syntax

    string.split(separator)

    The split() method accepts a parameter separator that breaks the string characters into array elements based on the separator.

    <script>
        var text = "Hi! There welcome to techgeekbuzz Hi!";
        var arr = text.split(" "); //split the text based on white space
        console.log(arr);
    </script>

    Output

    ["Hi!", "There", "welcome", "to", "techgeekbuzz", "Hi!"]

    Behind the code In the above example the text.split(" "); statement will split the text string characters into array elements value based on the white space. If we do not specify any parameter to the split() method it will take the complete string as a single array value.

    var text = "Hi! There welcome to techgeekbuzz Hi!";
    var arr = text.split(); 
    console.log(arr);
    Output
    ["Hi! There welcome to techgeekbuzz Hi!"]

    Summary

    • JavaScript string support all the methods and property available to JS String() object.
    • The length property returns the total number of characters present in the string.
    • To convert the string into uppercase and lowercase we have toUpperCase() and toLowerCase() methods.
    • To find the substring in a string we can either use, indexOf(), lastIndexOf() or search() method.
    • The split() method converts a string into an array based on the separator.

    People are also reading: